package core

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/cookiejar"
	"regexp"

	"google.golang.org/appengine"
	"google.golang.org/appengine/urlfetch"
)

////设置用户名和密码常量
const (
	USERNAME = "XXXX"
	PASSWORD = "*********"
)

//Vpgame 自動參加roll活動
func Vpgame(resp http.ResponseWriter, requ *http.Request) {
	cookieJar, _ := cookiejar.New(nil)
	//	client := &http.Client{Jar: cookieJar} //用于本地
	c := appengine.NewContext(requ)
	client := urlfetch.Client(c) //用于gae
	client.Jar = cookieJar
	urlStr := "http://passport.vpgame.com/login.html"
	formData := "Register%5Busername%5D=" + USERNAME + "&Register%5Bpassword%5D=" + PASSWORD + "&Register%5BrememberMe%5D=0"
	req, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(formData))
	req.Header.Set("Content-Type", "application/x-www-form-urlEncoded") //设定Content-Type，post参数才可正常传递。
	res, _ := client.Do(req)
	defer res.Body.Close() //登录成功
	urlStr = "http://dota2.vpgame.com/roll.html"
	req, _ = http.NewRequest("GET", urlStr, nil)
	res, _ = client.Do(req)
	defer res.Body.Close() //访问roll主页面
	output, _ := ioutil.ReadAll(res.Body)

	r := regexp.MustCompile(`(?s)<p class="btn-roll-ft" id="btn-roll-ft-([0-9]+)">\s<span class="btn btn-roll-room active">View Activity</span> </p>`)
	rollURL := r.FindAllString(string(output), -1) //获取所有可以参加的roll的url
	for i := range rollURL {
		urlStr = r.ReplaceAllString(rollURL[i], "http://dota2.vpgame.com/roll/${1}.html")
		req, _ = http.NewRequest("GET", urlStr, nil)
		res, _ := client.Do(req)
		defer res.Body.Close() //获取ROLL具体页面
		output, _ := ioutil.ReadAll(res.Body)

		//fmt.Println(string(output))
		r = regexp.MustCompile(`(?s)<a href="/roll/([0-9]+)\.html\?lang=zh_cn">.*?<a href="/user/([0-9]+)\.html">`)
		rollFormData := r.FindString(string(output))
		rollFormData = r.ReplaceAllString(rollFormData, "roll_id=${1}&roll_onwer_id=${2}&ps_input=show")
		//fmt.Println(rollFormData)
		urlStr = "http://dota2.vpgame.com/roll/small-join.html"
		req, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(rollFormData))
		req.Header.Set("Content-Type", "application/x-www-form-urlEncoded") //设定Content-Type，post参数才可正常传递。
		res, _ = client.Do(req)
		defer res.Body.Close() //参加活动
		output, _ = ioutil.ReadAll(res.Body)
		fmt.Fprintln(resp, string(output)) //json
	}
	fmt.Fprintln(resp, "done!!!")
}
